// 语音录制器-录制用户的声音->转为数据->通过webSocket传给后端
// 录制用户语音
export class VoiceRecorder{
  constructor(){
    this.isRecording=false;//是否录制
    this.stream = null
    this.processor = null
  }

  async startRecording(onAudioData) {//开始录音
    try {
      this.stream = await navigator.mediaDevices.getUserMedia({ audio: true })//打开麦克风
      const audioContext = new AudioContext()
      const source = audioContext.createMediaStreamSource(this.stream)
      this.processor = audioContext.createScriptProcessor(4096, 1, 1)
      
      this.processor.onaudioprocess = (e) => {
        if (!this.isRecording) return
        const audioData = this.processAudio(e.inputBuffer.getChannelData(0))
        onAudioData(audioData)
      }
      
      source.connect(this.processor)
      this.processor.connect(audioContext.destination)
      this.isRecording = true
      return true
    } catch (error) {
      console.error('录音启动失败:', error)
      return false
    }
  }
}